package com.server.orm;

import org.hibernate.Session;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;

public class HibernateManager {

    private static final HibernateManager instance = new HibernateManager();

    public static HibernateManager getInstance() {
        return instance;
    }


    private static org.hibernate.SessionFactory sessionFactory;

    private static Configuration configuration = new Configuration();
    private static StandardServiceRegistry serviceRegistry;

    public void init() {
        //这一步就是通过Configuration对象的configure方法来加载配置文件的，当然这个文件的路径是在src包下的，
        //当这个方法中没有参数是默认加载hibernate.cfg.xml文件，当其中有参数时，如参数为"abc"，则加载abc.xml文件
        configuration.configure("hibernate.cfg.xml");
        //加载完成后就要通过configuration实例建立SessionFactory实例
        serviceRegistry = new StandardServiceRegistryBuilder().configure().build();
        sessionFactory = configuration.buildSessionFactory(serviceRegistry);
    }

    /**
     * 获取session，所有的hibernate操作均基于session进行
     */
    public static Session getSession() {
        //获取Session实例
        return sessionFactory.getCurrentSession();
    }

    /**
     * 强制hibernate写库
     */
    public static void close() {
        Session session = HibernateManager.getSession();
        session.beginTransaction();
        session.flush();
        session.clear();//清除内部缓存的全部数据，及时释放出占用的内存
        session.close();
    }
}
